<template>
  <div class="problem-detail">
    <ul>
      <!-- 题目详细信息描述 -->
      <li class='leftDesc' >
        <!-- 评论/提交记录按钮 -->
        <div style="float: right;margin-right: 10px;margin-top: 20px;">
          <router-link  target="_blank" :to="'/main/comment?fatherId='+problem.id" style="margin: 10px;"><i class="fa fa-comments fa-lg"></i> {{$t('comment')}}</router-link>
          <router-link target="_blank" :to="'/main/status?problemId='+problem.id" style="margin: 10px;"><i class="fa el-icon-pie-chart fa-lg"></i> {{$t('submitRecord')}}</router-link>
        </div>
        <h2>{{ problem.title }}</h2>

        <div class="limit">
          <ul>
            <li>{{$t('problemMode.detail.titleCode')}}：{{ formatterCode(problem.code) }}</li>
            <li>{{$t('problemMode.save.timeLimit')}}：{{ problem.timeLimit }} ms</li>
            <li>{{$t('problemMode.save.memoryLimit')}}：{{problem.memoryLimit}} MB</li>
            <li>{{$t('problemMode.save.stackLimit')}}：{{problem.stackLimit}} MB</li>
          </ul>
        </div>

        <!-- 文档方式的题目，需跳转 -->
        <div v-if="problem.type==1" >
          <el-empty description="文档方式，不支持展示">
            <el-button @click="problemFilePush" type="primary">点击跳转</el-button>
          </el-empty>
        </div>
        <!-- 题目详细信息描述 -->
        <div v-if="problem.type==0">
        <h3>{{ $t('problemMode.save.desciption') }}</h3>
        <mavonEditor :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false" v-model="problem.description" style="min-height: 20px"/>

        <h4>{{ $t('problemMode.save.input') }}:</h4>
        <mavonEditor :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false"
         v-model="problem.input" style="min-height: 20px"/>
        <h4>{{ $t('problemMode.save.output') }}:</h4>
        <mavonEditor :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false"
         v-model="problem.output" style="min-height: 20px"/>
        </div>
         <!-- 测试用例 -->
         <div v-for="(item,index) in examples" :key="item.id">
          <h4>{{ $t('problemMode.detail.example') }} {{index+1}}:</h4>
          <div class="example">
            <div class="desc">{{ $t('problemMode.detail.input') }}</div>
            <div>
              <!-- <el-tag class="textq" type="info">{{ item.input }}</el-tag> -->
              <el-input  type="textarea" autosize disabled v-model="item.input" placeholder="">
              </el-input>
            </div>
            <div class="desc">{{ $t('problemMode.detail.output') }}</div>
            <div>
              <!-- <el-tag class="textq" type="info">{{ item.output }}</el-tag> -->
              <el-input  type="textarea" autosize disabled v-model="item.output" placeholder="" :style="'pointer-events: unset;'">
              </el-input>
            </div>
            <div v-if="!$MyUtils.isEmpty(item.description)">
              <div class="desc">{{ $t('problemMode.detail.explain') }}</div>
            <div style="margin: 5px;padding: 5px;">
<!--              {{ item.description }}-->
              <mavonEditor previewBackground="#eaf0f5" :boxShadow="false" :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false"
                           v-model="item.description" style="min-height: 20px"/>
            </div>
            </div>
          </div>
         </div>


      </li>

      <!-- 题目代码 -->
      <li style="position:relative;width: 100%;flex: 1;">
        <div class="code-header">
          {{ $t('language') }} :
          <!-- //语言选择 -->
          <el-select v-model="submitData.language" placeholder="c++/Java/python" style="width:150px;" @change="LangChange">
          <el-option label="C/C++" value="C++"></el-option>
          <el-option label="Java" value="Java"></el-option>
          <el-option label="Python" value="Python"></el-option>
          </el-select>
          <!-- 清空代码 -->
          <el-button @click="clearCode" :title="$t('problemMode.detail.right.clear')" icon="el-icon-refresh" circle style="margin-left: 10px;"></el-button>

        </div>
        <!-- 代码 -->
        <div class="code-1">
          <codemirror  style="border: 2px solid #ececec;height: 52vh" v-model="submitData.code" :options="cmOptions"></codemirror>

        </div>
        <!-- 提交自测按钮 -->

        <div class="code-submit"
        v-loading="submitLoading"  :element-loading-text="loadingText">
          <!-- 填入测试数据 -->
          <el-tabs type="border-card">
          <el-tab-pane :label="$t('problemMode.detail.right.MyselfTestInput')">
            <el-input v-model="submitData.testInput" type="textarea" :autosize="{ minRows: 7, maxRows: 7}"
              :placeholder="$t('problemMode.detail.input')" :maxlength="500" show-word-limit style="width:49%"> </el-input>
            <el-input v-model="submitData.testOutput" type="textarea" :autosize="{ minRows: 7, maxRows: 7}"
            :placeholder="$t('problemMode.detail.output')" :maxlength="500" show-word-limit style="width:49%;margin-left: 2%;"> </el-input>
            <!-- 填入测试用例 -->
            <!-- <el-tag style="margin: 5px;" size="small" v-for="(item,index) in examples" :key="item.id" type="info"></el-tag> -->
            <el-button  style="margin: 8px;" size="mini" v-for="(item,index) in examples" :key="item.id" type="success" plain @click="writeCase(item)">
              {{$t('problemMode.detail.right.loadExample')}}  {{ index+1 }}</el-button>
              <div v-if="!(examples&&examples.length>0)" style="height:2.74rem"></div>
          </el-tab-pane>



          <el-tab-pane :label="$t('problemMode.detail.right.runSerult')" >
            <!-- 撑开，结果 -->
              <div style="height:158px;">
                <!-- 注意信息 -->

                <div v-show="submitResultFlag==1&&isEmpty(testResult.id)" class="code-submit-attention submit-success">
                  {{ $t('problemMode.detail.right.testSuccess') }}
                </div>
                <!-- 成功 -->
                <div v-show="submitResultFlag>0" :class="submitResultFlag==1?'code-submit-attention submit-success':'code-submit-attention submit-error'" >
                  <span v-show="submitResultFlag==2">
                    {{ testResult.msg }}
                   </span>
                  <span v-show="submitResultFlag==1&&isEmpty(testResult.id)">
                    {{$t('problemMode.detail.right.testAssc')}}
                    <!-- 自测通过 -->
                  </span>
                  <span v-show="submitResultFlag==1&& !isEmpty(testResult.id)">
                    <!-- 答案正确 -->
                    {{ $t('problemMode.detail.submit.right') }}
                  </span>
                   <i class="el-icon-timer fa-lg"></i>{{$t('problemMode.detail.right.runTime')}} {{testResult.time}} ms <i class="el-icon-cpu fa-lg"></i>{{$t('problemMode.detail.right.runMemory')}} {{testResult.memory}} KB
                </div>
                <div v-show="submitResultFlag==1&&!isEmpty(testResult.id)" style="margin: 10px;color:#32ca99;font-size: 75%;">
                  <!-- 答案正确:恭喜！您提交的程序通过了所有的测试用例 -->
                  {{$t('problemMode.detail.right.successMsaaage')}}
                </div>
                <div style="background-color: #f7f8f9;padding: 10px;font-size: 75%;" v-show="submitResultFlag==2&&isEmpty(testResult.id)">
                  <div style="margin-left: 10px;margin-top: 10px;">
                    <!-- 预期输出： -->
                    {{ $t('problemMode.detail.right.expectedOutput') }}:
                    <span>{{ submitData.testOutput }}</span></div>

                  <div style="margin-left: 10px;margin-top: 10px;">
                    <!-- 实际输出： -->
                    {{ $t('problemMode.detail.right.actualOutput') }}:
                    <span>{{ $MyUtils.isEmpty(testResult.data)?testResult.errorMsg:testResult.data}}</span></div>
                  <!-- <div v-show="!isEmpty(testResult.errorMsg)">提示信息：<span style="width:100% background-color:#f7f8f9">{{ testResult.errorMsg }}</span></div> -->
                </div>

              </div>
              <!-- 占位 -->
              <div style="height:2.74rem"></div>
          </el-tab-pane>


          <el-button type="success" style="float:right;margin-bottom: 10px;margin-top: -40px;" @click="submitSave">
            <!-- 保存并提交 -->
            {{ $t('problemMode.detail.right.saveAndSubmit') }}
          </el-button>
          <el-button style="border-color: #32ca99;color:#32ca99;float:right;margin-bottom: 10px;margin-top: -40px;margin-right: 10px;"
           plain icon="fa fa-play" @click="testSubmit">
            <!-- 自测运行 -->
            {{ $t('problemMode.detail.right.selfTestRun') }}
          </el-button>

        </el-tabs>

        </div>
      </li>
    </ul>
    <!-- <div style="height:200px"></div> -->
  </div>
</template>

<script lang="ts">
import * as problemApi from '@/api/problem'
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';

// 代码编译器
// require component
import { codemirror } from 'vue-codemirror'

// require styles
import 'codemirror/lib/codemirror.css'
// 引入语言
import 'codemirror/mode/javascript/javascript'
import 'codemirror/mode/clike/clike'
import 'codemirror/mode/htmlmixed/htmlmixed'
import 'codemirror/mode/http/http'
import 'codemirror/mode/python/python'
import 'codemirror/mode/http/http'
import 'codemirror/mode/sql/sql'
import 'codemirror/mode/vue/vue'
import 'codemirror/mode/xml/xml'
import 'codemirror/mode/lua/lua'
// 引入样式
import 'codemirror/theme/base16-dark.css'
import 'codemirror/theme/neat.css'
import 'codemirror/theme/idea.css'
import 'codemirror/addon/dialog/dialog.css'
import 'codemirror/addon/dialog/dialog'
import 'codemirror/addon/search/searchcursor'
import 'codemirror/addon/search/search'
import 'codemirror/addon/search/jump-to-line'
import 'codemirror/addon/search/matchesonscrollbar'
import 'codemirror/addon/search/match-highlighter'
// #endregion
// #region 代码提示功能
// 具体语言可以从 codemirror/addon/hint/ 下引入多个
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/show-hint.js'
import 'codemirror/addon/hint/anyword-hint'  // 简易的代码提示功能
// #endregion
// #region 高亮行功能
import 'codemirror/addon/selection/active-line'
import 'codemirror/addon/selection/selection-pointer'
// #endregion
// #region 覆盖scrollbar样式功能
import 'codemirror/addon/scroll/simplescrollbars.css'
import 'codemirror/addon/scroll/simplescrollbars'
// #endregion
//  #region 自动括号匹配功能
import 'codemirror/addon/edit/matchbrackets.js'
// #endregion
// 显示自动刷新
import 'codemirror/addon/display/autorefresh.js'
import 'codemirror/addon/lint/lint.js'
import 'codemirror/addon/lint/lint.css'
// #region  代码段折叠功能
import 'codemirror/addon/fold/foldcode.js'
import 'codemirror/addon/fold/foldgutter.js'
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/brace-fold.js' // 括号折叠
import 'codemirror/addon/fold/comment-fold.js'
import 'codemirror/addon/fold/indent-fold.js' // 缩进折叠
import 'codemirror/addon/fold/comment-fold.js'
//括号不全
import 'codemirror/addon/edit/closebrackets.js'

//data映射数据
import ModeData from '@/assets/data'
export default {
  name: 'problemDetail',
  data() {
    return {
      problem:{description:""},
      examples:[],
      submitData:{}, //提交的代码信息
      cmOptions: {  //代码编译器配置
        tabSize: 4, // 制表符的宽度
        mode: 'text/x-java',
        lineNumbers: true,
        line: true,

        // 主题
        theme: 'idea',
        // 显示函数
        // 显示行号
        // 软换行
        lineWrapping: true,
        cursorScrollMargin: 5,
        extraKeys: {},
        // 高亮行功能
        styleActiveLine: true,
        // 调整scrollbar样式功能
        // scrollbarStyle: 'overlay',
        // 自动括号匹配功能
        matchBrackets: true,
        autofocus: true,
        autoRefresh: true,
        // #region 代码折叠
        foldGutter: true,
        // foldOptions: { scanUp: true },
        gutters: [
          'CodeMirror-linenumbers',
          'CodeMirror-foldgutter',
          'CodeMirror-lint-markers'
        ],
        // #endregion
        showHint: true,
        lint: true,
        hintOptions: {
          // 避免由于提示列表只有一个提示信息时，自动填充
          completeSingle: false
        },
        autoCloseBrackets:true, //自动补全括号

      },
      submitResultFlag:0,  //自测,0未测，1成功，2表示失败，
      testResult:{},  //运行结果
      submitLoading:false,  //加载中
      loadingText:this.$t('problemMode.detail.submit.submiting'),
    }
  },
  components: {
    mavonEditor,   //markdown编译器
    codemirror,  //代码编译器
  },
  methods: {

    //文件方式的题目，跳转文档
    problemFilePush(){
                //该题目是以文件方式
          // this.$router.push({path:"/api/problem/download/"+data.id})
      problemApi.downLoadProblem({"id":this.problem.fileId}).then(res=>{
        var blob = new Blob([res.data], { type: "application/pdf" });
        console.info(blob);
        var file = (window.URL || window.webkitURL).createObjectURL(blob);
        window.open(file,"_blank")
      })
    },
    //判断是否满足提交条件
    isSubmit(){
      if(this.isEmpty(this.submitData.language)){
        this.$message({message:"未选择编译语言",type:"warning"})
        return false;
      }

      if(this.isEmpty(this.submitData.code)){
        this.$message({message:"代码不能为空",type:"warning"})
        return false;
      }
      return true;
    },
    //自测运行
    testSubmit(){
      // console.info(document.querySelector("#tab-1"))

      if(!this.isSubmit())return;
      if(this.isEmpty(this.submitData.testOutput)){
        this.$message({message:"未输入测试数据",type:"warning"})
        return false;
      }
      this.loadingText = "提交中";

      this.submitLoading = true;
      problemApi.testSubmitApi(this.submitData).then(res=>{
        // console.info(res);
        this.submitLoading = false;
        document.getElementById("tab-1").click();  //展示结果
        this.testResult = res.data.data;
        if(res.data.data.status==0){//结果正确
          this.submitResultFlag = 1;
        }else{
          this.submitResultFlag = 2;
        }
      })
    },
    //正式提交
    async submitSave(){
      if(!this.isSubmit())return;
      this.submitLoading = true;
      this.loadingText = this.$t('problemMode.detail.submit.submiting');
      const submitId = await problemApi.submitSaveApi(this.submitData).then(res=>{
        return res.data.data;
      })
      if(submitId){
          //获取sumit id,根据id查询结果
        this.loadingText = this.$t('problemMode.detail.submit.submited');
        this.testResult = await problemApi.getSubmitResultApi({"id":submitId}).then(res=>{
          return res.data.data;
        })
        document.getElementById("tab-1").click();  //展示结果
        // 每过一段时间查询一次
        // 定时事件,刷新失败
        // var myVar=setInterval(function(){
        //   problemApi.getSubmitResultApi({"id":submitId}).then(res=>{
        //     this.testResult = res.data.data;
        //     if(this.testResult.errorStatus!=7){
        //       this.submitLoading = false;
        //       window.clearInterval(myVar)
        //     }else if(this.testResult.status==1){
        //       this.loadingText = "队列中";
        //     }else if(this.testResult.status==2){
        //       this.loadingText = "编译中";
        //     }else if(this.testResult.status==3){
        //       this.loadingText = "运行中";
        //     }
        //   })
        // },500);
        // while循环查询
        var waiTime = 1000;
        while(this.testResult.errorStatus==7){ //运行中,再次询问
          this.MySleep(waiTime*=1.5)//休息一会
          this.testResult = await problemApi.getSubmitResultApi({"id":submitId}).then(res=>{
            return res.data.data;
          })

          this.loadingText = ModeData.submit.status[this.testResult.errorStatus];
        }
        this.submitLoading = false;
        if(this.testResult.errorStatus==0)this.submitResultFlag = 1;
        else this.submitResultFlag = 2;
        this.testResult.msg = ModeData.submit.status[this.testResult.errorStatus]
      }else{
        this.submitLoading = false;
      }
    },
    //填入测试用例
    writeCase(data){
      // console.info(data);
      this.submitData.testInput = data.input;
      this.submitData.testOutput = data.output;
      //显示延迟??
      this.submitData = JSON.parse(JSON.stringify(this.submitData))
      // console.info(this.submitData);
    },
    LangChange(){  //选择编译器语言
      if(this.submitData.language =='Java')this.cmOptions.mode = 'text/x-java';
      else if(this.submitData.language == 'Python')this.cmOptions.mode = 'text/x-python';
      else this.cmOptions.mode = 'text/x-c++src';
      // console.info(this.submitData.language,this.cmOptions.mode)
    },
    clearCode(){
      // 刷新后代码框将重置为初始状态，正在编辑的代码将清空，但不会影响已提交的代码，确定刷新吗？
      this.$confirm(this.$t('problemMode.detail.right.clearMsg'), this.$t('prompt'), {
          confirmButtonText: this.$t('save'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }).then(() => {
          this.submitData.code = "";
        })
    },
    //获取题目详情
    getById(){
      problemApi.getOneById({"id":this.$route.params.id}).then(res=>{
        if(res.data.code==10000){
            this.problem = res.data.data;
            //填入
            this.submitData.problemId = this.problem.id;
          this.getExamplesCase();
          this.lastSubmitByProblemId();
        }
      })
    },
    // 获取题面的测试用例
    getExamplesCase(){
      problemApi.getExampleCase({"id":this.$route.params.id}).then(res=>{
        this.examples = res.data.data;
      })
    },
    //重新输出编码
    formatterCode(code) {
        // console.info(row,column);
        var res = "" + code;
        while (res.length < 4)
            res = "0" + res;
        return "P" + res;
    },
    isEmpty(data){
      return (!data)||data=='';
    },
    MySleep(data){
      var iTime = new Date().getTime();
      while(new Date().getTime()-iTime<data){
        // if(new Date().getTime()-iTime>=data)break;
      }
    },
    // 获取上次提交记录
    lastSubmitByProblemId(){
      problemApi.getLastSubmit({"id":this.$route.params.id}).then(res=>{
        if(res.data.data){
          this.submitData.code = res.data.data.code+"";
          this.submitData.language = res.data.data.language+"";
          this.submitData = JSON.parse(JSON.stringify(this.submitData))
          this.testResult = res.data.data;
          if(res.data.data.errorStatus==0)this.submitResultFlag = 1;
          else this.submitResultFlag = 2;
          this.testResult.msg = ModeData.submit.status[this.testResult.errorStatus]
        }
      })
    }

  },
  created(){
    this.getById();


  }


}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

a{
  /* color: #000; */
  text-decoration: none;
}
.problem-detail .code-header{
  margin: 10px;
  font-size: 85%;
  font-family: Lucida Console;
}
.problem-detail > ul > li{
  height: 100%;
  list-style: none;
  display:inline-block;
  margin: .3125rem;
  background-color: #ffffff;
  border-radius: 1rem;
  overflow-y: auto;
  overflow-x: hidden;
  box-shadow: 2px 2px 2px 2px #afafafaf;
  padding-left: 10px;
  padding-right: 10px;
  padding-bottom: 10px;

}
.problem-detail > ul .leftDesc{
  width:47%;
  resize: horizontal;
  position: relative;
}
.problem-detail > ul{
  padding: 0px;
  text-align: left;
  height: 88vh;
  margin: 0px;
  display: flex;
  padding-right: 0px;
}
/* .leftDesc::-webkit-scrollbar {
  width: 10px;
  height: inherit;
} */
.problem-detail{
  height:87%;
  padding: 0px;
  margin: 0px;
}
.problem-detail .markdown-body{
  margin-top: 10px;
}

.problem-detail .example{
  background-color: #eaf0f5;
  border-radius: 5px;
  padding: 10px;
}
.problem-detail .example .desc{
  margin: 5px;
  font-size: 85%;
}
.problem-detail .example .textq{
  width: 100%;
  font-family: Lucida Console;

}
.problem-detail .limit{
  width: 98%;
  border-radius: 8px;
  background-color: #ebebeb;
  padding: 10px;
}
.problem-detail .limit > ul >li{
  text-align: left;
  list-style: none;
  margin: 5px;
  font-size: 90%;
}
.problem-detail .limit > ul{
  text-align: left;
  padding: 0px;
}



.problem-detail .code-submit{
  font-family: Lucida Console;
  font-size: 90%;
}
.problem-detail .code-submit-attention{

  width: 97%;
  padding: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
  font-size: 75%;
}
.problem-detail .submit-success{
  background-color: #eefaf7;
  color: #68ca99;

}
.problem-detail .submit-error{
  background-color: #ffe7e7;
  color: #ea0e07;
  font-weight: 700;

}


.problem-detail .CodeMirror-wrap{
  min-height: 52vh;
}
</style>
<style>
.problem-detail .code-1 .CodeMirror-scroll{
  height: 52vh;
}
.CodeMirror {
  overscroll-y: scroll !important;
  height: auto !important;
}
</style>
